LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.numeric_std.all;

ENTITY KeySender IS
	PORT
	(
		Clk : IN std_logic;
		Reset : IN std_logic;
		Enable : IN std_logic;
		Txd_SendData : OUT std_logic_vector(7 DOWNTO 0);
		SendEnable : OUT std_logic;
		SendBusy : IN std_logic;
		P2KeyState : IN std_logic_vector(5 DOWNTO 0)
	);
END ENTITY;

ARCHITECTURE rtl OF KeySender IS
	TYPE State_Type IS (Idle, Init, Sending, Sending_Wait);
	SIGNAL state : State_Type;
BEGIN
	Txd_SendData <= "00" & P2KeyState;	-- 00 means keyboard;
	
	cMainCtl : PROCESS(Clk, Reset)
	BEGIN
		IF Reset = '0' THEN
			state <= Idle;
		ELSIF rising_edge(Clk) THEN
			CASE state IS
				WHEN Idle =>
					IF Enable = '1' THEN
						state <= Sending;
					ELSE
						state <= Idle;
					END IF;
				WHEN Sending =>
					SendEnable <= '1';
					state <= Sending_Wait;
				WHEN Sending_Wait =>
					SendEnable <= '0';
					IF SendBusy = '0' THEN
						state <= Sending;
--						SendEnable <= '1';
					ELSE
						state <= Sending_Wait;
					END IF;
				WHEN OTHERS =>
			END CASE;
		END IF;
	END PROCESS;
END rtl;
